<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <template #footer>
      <a-button @click="closeModal">取消</a-button>
      <a-button type="primary" @click="clearMath">清除</a-button>
      <a-button type="primary" @click="handleSubmit">确定</a-button>
    </template>
    <div class="">
      <div>
        <InputTextArea readonly v-model:value="mathValue" />
        <div class="flex">
          <Card :bordered="false" :head-style="headStyle" title="回写表单" class="w-2/5">
            <ScrollContainer>
              <div class="max-h-350px">
                <div
                  v-for="(item, index) in fieldsDataOptions"
                  :key="'fields' + index"
                  class="cursor-pointer"
                  @click="handleFieldsClick(item)"
                >
                  {{ item['label'] }}
                </div>
              </div>
            </ScrollContainer>
          </Card>
          <Card :bordered="false" :head-style="headStyle" title="表达式" class="w-1/5">
            <div class="flex flex-wrap w-79px border-t-1 border-l-1 border-gray-400 border-solid">
              <div
                class="w-39px h-39px flex justify-center items-center cursor-pointer border-b-1 border-r-1 border-gray-400 border-solid"
                v-for="item in calcList"
                :key="item.value"
                @click="handleCalc(item.value)"
              >
                {{ item.label }}
              </div>
            </div>
          </Card>
          <Card :bordered="false" :head-style="headStyle" title="主表单" class="w-2/5">
            <ScrollContainer>
              <div class="max-h-350px">
                <template v-if="kind == 1">
                  <div
                    v-for="(item, index) in concatFiels"
                    :key="'concatFiels' + index"
                    class="cursor-pointer"
                    @click="handleFieldsClick(item)"
                  >
                    {{ item['title'] }}
                  </div>
                </template>
                <template v-else>
                  <div
                    v-for="(item, index) in mainFormFields"
                    :key="'mainFormFields' + index"
                    class="cursor-pointer"
                    @click="handleFieldsClick(item)"
                  >
                    {{ item['title'] }}
                  </div>
                </template>
              </div>
            </ScrollContainer>
          </Card>
        </div>
      </div>
      <div class="ml-2">注：如果字段为字符串型，置值为常量时，需加单引号，如：'someVal'</div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import type { CSSProperties, PropType } from 'vue';
  import { defineComponent, ref, computed, unref, reactive } from 'vue';
  import { Input, Table, Select, TreeSelect, Radio, Card } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { FormDataOptions } from '../../writeback.data';
  import { useFlowStore } from '/@/store/modules/flow';
  import { isArray } from '/@/utils/is';

  import { getFormGetNestFieldsWithFormName, getFormGetFields } from '/@/api/flowManage/flowManage';
  import { calcList } from './configModulesModal.data';
  import { ScrollContainer } from '/@/components/Container';
  export default defineComponent({
    name: 'ConfigrationCombinationModal',
    components: {
      BasicModal,
      Card,
      ScrollContainer,
      Input,
      InputTextArea: Input.TextArea,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      //   const useFlow = useFlowStore();
      const getTitle = '配置';
      const mathValue = ref('');
      const hiddenVal = ref('');
      const kind = ref(0);
      const formCode = ref('');
      const fieldsDataOptions = ref<FormDataOptions[]>([]);
      const type = ref(1);
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        setModalProps({ confirmLoading: false, width: '1000px' });
        fieldsDataOptions.value = [];
        try {
          mathValue.value = data?.mathValue?.trim() ? data?.mathValue : '';
          hiddenVal.value = unref(mathValue) ? '1' : '';
          formCode.value = data?.formCode;
          kind.value = data?.kind;
          type.value = data?.type;
          await getFormGetNestFieldsWithFormNameData();
          if (unref(kind) == 1) {
            fieldsDataOptions.value = data?.fields;
            if (isArray(fieldsDataOptions.value)) {
              if (unref(type) == 1) {
                fieldsDataOptions.value.forEach((item) => {
                  item.value = `{${item.title}}`;
                  item.label = item.title;
                });
              } else {
                fieldsDataOptions.value.forEach((item) => {
                  item.value = `{${item.label}}`;
                });
              }
            }
          } else {
            fieldsDataOptions.value = fieldsWithNestList.value;
          }
          getMainFormFields();
        } catch (err) {
          console.log(err);
        }
      });
      const fieldsWithNestList = ref([]);
      //主嵌套表字段
      const getFormGetNestFieldsWithFormNameData = async () => {
        let params = {
          formCode: unref(formCode),
        };
        await getFormGetNestFieldsWithFormName(params).then((res) => {
          let data = res || [];
          data.forEach((item) => {
            item.value = `{$nest.${item.formCode}.${item.title}}`;
            item.title = `${item.formName}-${item.title}`;
            item.label = item.title;
          });
          fieldsWithNestList.value = data;
        });
      };

      //主表字段
      const mainFormFields = ref<Recordable[]>([]);
      const getMainFormFields = async () => {
        let params = {
          formCode: unref(formCode),
        };
        await getFormGetFields(params).then((res) => {
          let data = res || [];
          data.forEach((item) => {
            delete item.options;
            item.value = `{$${item.title}}`;
          });
          data.unshift({ name: 'id', title: 'ID', value: '{$id}' });
          mainFormFields.value = data;
        });
      };

      const concatFiels = computed(() => [...unref(mainFormFields), ...unref(fieldsWithNestList)]);

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });

          closeModal();
          emit('success', { mathValue: unref(mathValue), kind: unref(kind) });
        } catch (err) {
          console.log(err);
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      //字段点击
      const handleFieldsClick = (record) => {
        let math = unref(mathValue);
        let code = record.value;
        // let reg = /^(\{[\w\W]+\})|[\d]+$/;
        let reg1 = /^[\+\-\*\/]$/;
        let hiddenVal2 = unref(hiddenVal);
        if (hiddenVal2 != '' && !reg1.test(hiddenVal2)) {
          return;
        }
        mathValue.value = math + code;
        hiddenVal.value = code;
      };

      //单击计算
      const handleCalc = (val) => {
        let code = val;
        let math = unref(mathValue);
        let reg = /^(\{[\w\W]+\})|[\d]+$/;
        let reg1 = /^[\+\-\*\/]$/;
        let reg2 = /^\d+$/;
        let hiddenVal2 = unref(hiddenVal);
        if (reg.test(hiddenVal2)) {
          if (!reg2.test(hiddenVal2) && !reg1.test(code)) {
            return;
          }
        } else {
          if (reg1.test(code)) {
            return;
          }
        }
        mathValue.value = math + code;
        hiddenVal.value = code;
      };

      //清空
      const clearMath = () => {
        mathValue.value = '';
        hiddenVal.value = '';
      };

      return {
        registerModal,
        getTitle,
        handleSubmit,
        headStyle: {
          textAlign: 'center',
        } as CSSProperties,
        fieldsDataOptions,
        handleFieldsClick,
        calcList,
        handleCalc,
        mathValue,
        kind,
        concatFiels,
        mainFormFields,
        clearMath,
        closeModal,
      };
    },
  });
</script>
